//
//  PictureView.swift
//  Weibo
//
//  Created by 5201-mac on 2017/4/19.
//  Copyright © 2017年 wlb-mac. All rights reserved.
//

import UIKit

class PictureView: UIView {
    
    //添加模型数组的属性
    var pictures: [PictureItem]? {
        didSet {
            //遍历子视图，先隐藏所有的坑
            for subView in subviews as! [UIImageView]{
                subView.isHidden = true
                //cell有复用的特性
                subView.image = nil
            }
            
            let count = pictures?.count ?? 0
            //通过SDWebImage设置服务器图片
            var index = 0
            for pictureItem in pictures! {
                if count == 4 && index == 2{
                    //做特殊操作
                    index += 1
                }
                
                //根据index获取模型
                let imageView = subviews[index] as! UIImageView
                //设置显示
                imageView.isHidden = false
                //设置url异步加载网络图片
                let url = NSURL(string: pictureItem.thumbnail_pic ?? "")
                imageView.sd_setImage(with: url as URL!)
                index += 1
            }
        }
    }

    //添加九张图片
    //从xib中激活的时候会调用这个方法，和viewDidLoad方法类似
    override func awakeFromNib() {
        let count = 9
        for _ in 0..<count {
            let imageView = UIImageView()
            imageView.backgroundColor = randomColor()
            self.addSubview(imageView)
            print(self)
            //不能在这个方法中设置frame
        }
    }
    
    override func layoutSubviews() {
        super.layoutSubviews()
        for (index,subView) in subviews.enumerated() {
            //确定行数和列数
            let rowIndex = index / colCount
            let colIndex = index % colCount
            //设置frame
            let ivX = (itemWidth + cellMargin) * CGFloat(colIndex)
            let ivY = (itemWidth + cellMargin) * CGFloat(rowIndex)
            subView.frame = CGRect(x: ivX, y: ivY, width: itemWidth, height: itemWidth)

        }
    }
}
